<?
	include_once "../../include/conn.php";
	include_once "../../api/config.php";
	/**************************************
	* ************ 主统计接口 ***********
	* ************************************/
	// 接收数据
	$sid        = intval($_POST['sid']);
	$province   = $_POST['province'];
	$provinceid = $_POST['provinceid'];
	$city       = $_POST['city'];
	$cityid     = $_POST['cityid'];
	$area       = $_POST['area'];
	$areaid     = $_POST['areaid'];
	$scope      = $_POST['scope'];
	$scopeid    = $_POST['scopeid'];
	$fullAddr   = strlen($_POST['fullAddr'])>1 ? $_POST['fullAddr']: '未发送数据';


	// 找出相关问卷
	// 目前使用全地址字段来匹配
	$results = array('code' => 0,'msg'=>'数据正常返回');//用于正常有数据输出的
	$cmd = "
	select 
		#********问卷********
		qn.sid,qn.qn_no,qn.unionid,qn.answer_result
		#********用户********
		,u.contact_name,u.contact_tel,u.company
		#********公司********
		,c.title,c.size,c.full_addr,c.province,c.province_id,c.city,c.city_id,c.area,c.area_id,c.scope,c.scope_id
		
		from 
		vbyzc_vote_qn qn
		left join vbyzc_user u on u.unionid = qn.unionid
		left join vbyzc_company c  on c.id= u.company
		where qn.sid = $sid and c.full_addr like '%$fullAddr%'
	";

	$rs            = mysql_query($cmd) or die(mysql_error());
	$array_user    = Array(); #用于计算用户数量
	$array_company = Array(); #用于计算公司数量
	$array_result  = Array(); #一个储存所有问卷答案的数组
	$array_statistic = Array();

	// 遍历问卷记录， 每张问卷的数据取出来
	while($row = mysql_fetch_assoc($rs)){
		$array_user   [$row['unionid']] = '';
		$array_company[$row['title']]   = '';
		$answer_result = json_decode($row['answer_result'],ture); #结果转为json数据，加参数true转成数组，否则是class对象
		$array_result[] = Array(
			"sid"           => $row['sid']
			,"unionid"       => $row['unionid']
			,"company"       => $row['title']
			,"answer_result" => $answer_result
		);

		// 遍历每个答案组部分，统计数据
		foreach ($answer_result as $key => $value) {
			// print_r($value);
			# 按公司名称当成键名，一行得分，一行空缺分
			$array_statistic[$value['name']] = $array_statistic[$value['name']] + $value['score'] ; 
			$array_statistic["{$value['name']}空缺"] = $array_statistic["{$value['name']}空缺"] + ($value['score_full']-$value['score']);
		}

	}
	// $results ['dataList']     = $array_result;          //所有答案数据
	$results ['countUser']    = count($array_user);
	$results ['countCompany'] = count($array_company);
	$results ['countQn']      = count($array_result);
	$results ['statistic']    = $array_statistic;


	// print_r( $array_user );
	// print_r( $array_company );
	// print_r( $array_result );
	// print_r($array_statistic);

	// //////////////////输出数据////////////////////////////////
	echo decodeUnicode(json_encode($results));
	mysql_close();
?>